﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ResxLocalizationEditor {
    class CsvResourceWriter : ResourceWriter {
        
        protected override void LoadCore(Resource resouce, string filePath) {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Writes a single resource to a CSV file.
        /// </summary>
        public void WriteSingleResource(ResourceSet set, Resource resource, string filePath) {
            WriteCore(set, resource, filePath);
        }

        protected override void WriteCore(ResourceSet set, Resource resource, string filePath) {
            using (var s = new FileStream(filePath, FileMode.Create)) {
                using (var sw = new StreamWriter(s)) {
                    sw.WriteLine("Key,Value,Comment");
                    
                    foreach (var key in (from k in set.Keys orderby k select k)) {
                        WriteCsvValue(sw, key);
                        sw.Write(',');
                        if (resource.ValueMap.ContainsKey(key))
                            WriteCsvValue(sw, resource.ValueMap[key]);
                        sw.Write(',');
                        if (resource.Comments.ContainsKey(key))
                            WriteCsvValue(sw, resource.Comments[key]);
                        sw.WriteLine();
                    }
                }
            }
        }

        private void WriteCsvValue(StreamWriter writer, string value) {
            if (value.Contains('"'))
                value = value.Replace("\"", "\"\""); //escape double quotes

            writer.Write("\"{0}\"", value);
        }

    }
}
